const $config = require('../nuxt.config.js')
const $axios =require('axios'); 
const timeago = require('../lib/timeago');

module.exports = function (Data) {
    // 从Elasticsearch 查询数据 
     Data.getRegion= async function () {
        let q ={
            "query" : {
                "bool":{
                    // "must":[
                    //     { "match": { "type": "topic"}},
                    //     { "match": { "cid": 3}}
                    // ],
                    "filter":[ 
                        {"term" : { "type" : "topic"}},
                        {"term" : { "cid" : 3}},
                        {"term" : { "deleted" : 0}},
                        { "exists" : { "field" : "region" }}
                     ]
            
                }
            } ,
            "aggs" : {
                "region" : {
                    "terms" : {
                      "field" : "region",
                      "order": {
                        "_count" : "desc" 
                      }
                    }
                }
            }
           
        }
        let res = await Data.getDocs(q,0,0);
        let buckets =  res.raw && res.raw.aggregations && res.raw.aggregations.region && res.raw.aggregations.region.buckets
        ////console.log(buckets)
        let region={};
        for (const bucket of buckets) {
           var regions =  Data.replaceAll("_"," ",bucket.key)
             regions = regions.split(",");
            var v = {
                name:regions[0]?(regions[0]+","+regions[1]): regions[1],
                city:regions[0],
                province:regions[1],
                country:regions[2],
                count:bucket.doc_count
           };
           
            if(!(region[regions[2]] instanceof Array )){
                region[regions[2]]=[] ;
            }
             
            region[regions[2]].push(v);
        }
        res.data = region;
        // ////console.log("region:", JSON.stringify(region))
        // ////console.log("buckets:",buckets,"q:",q,"res:", JSON.stringify( res));
		return res;
	};
   
    
}